import { apiClient, styleReGenClient } from './config'
import type { ApiResponse, PageResponse } from '@/types/user'
import type {
  Picture,
  PictureVO,
  PictureUploadRequest,
  PictureEditRequest,
  PictureUpdateRequest,
  PictureQueryRequest,
  PictureTagCategory,
  PictureReviewRequest,
  PictureBatchUploadRequest,
  PictureBatchUploadVO,
  DeleteRequest,
  PictureReviewCountVO,
  SearchPictureByColorRequest,
  PictureStyleRegenRequest,
} from '@/types/picture'

// 图片API接口

/**
 * 上传图片
 * @param file 图片文件
 * @param request 上传请求参数
 */
export const uploadPicture = async (
  file: File,
  request: PictureUploadRequest = {},
): Promise<ApiResponse<PictureVO>> => {
  const formData = new FormData()
  formData.append('file', file)

  // 将请求参数作为query参数传递
  const params = new URLSearchParams()
  if (request.id) params.append('id', request.id.toString())
  if (request.fileUrl) params.append('fileUrl', request.fileUrl)
  if (request.picName) params.append('picName', request.picName)
  if (request.spaceId) params.append('spaceId', request.spaceId)

  return apiClient.post(`/picture/upload?${params.toString()}`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

/**
 * 编辑图片
 * @param request 编辑请求
 */
export const editPicture = async (request: PictureEditRequest): Promise<ApiResponse<boolean>> => {
  return apiClient.post('/picture/edit', request)
}

/**
 * 更新图片（管理员）
 * @param request 更新请求
 */
export const updatePicture = async (
  request: PictureUpdateRequest,
): Promise<ApiResponse<boolean>> => {
  return apiClient.post('/picture/update', request)
}

/**
 * 删除图片
 * @param request 删除请求
 */
export const deletePicture = async (request: DeleteRequest): Promise<ApiResponse<boolean>> => {
  return apiClient.post('/picture/delete', request)
}

/**
 * 分页获取图片列表（用户）
 * @param request 查询请求
 */
export const listPictureVOByPage = async (
  request: PictureQueryRequest = {},
): Promise<ApiResponse<PageResponse<PictureVO>>> => {
  return apiClient.post('/picture/list/page/vo', request)
}

/**
 * 分页获取图片列表（管理员）
 * @param request 查询请求
 */
export const listPictureByPage = async (
  request: PictureQueryRequest = {},
): Promise<ApiResponse<PageResponse<Picture>>> => {
  return apiClient.post('/picture/list/page', request)
}

/**
 * 根据图片ID搜索图片（用户）
 * @param id 图片ID
 */
export const getPictureVOById = async (id: string): Promise<ApiResponse<PictureVO>> => {
  return apiClient.get(`/picture/get/vo?id=${id}`)
}

/**
 * 根据图片ID搜索图片（管理员）
 * @param id 图片ID
 */
export const getPictureById = async (id: string): Promise<ApiResponse<Picture>> => {
  return apiClient.get(`/picture/get?id=${id}`)
}

/**
 * 获取图片标签和分类
 */
export const listPictureTagCategory = async (): Promise<ApiResponse<PictureTagCategory>> => {
  return apiClient.get('/picture/tag_category')
}

/**
 * 图片审核
 * @param request 审核请求
 */
export const reviewPicture = async (
  request: PictureReviewRequest,
): Promise<ApiResponse<boolean>> => {
  return apiClient.post('/picture/review', request)
}

/**
 * 批量上传图片
 * @param files 图片文件列表
 * @param request 批量上传请求参数
 */
export const batchUploadPictures = async (
  files: File[],
  request: PictureBatchUploadRequest = {},
): Promise<ApiResponse<PictureBatchUploadVO>> => {
  const formData = new FormData()

  // 添加文件
  files.forEach((file) => {
    formData.append('files', file)
  })

  // 将请求参数作为query参数传递
  const params = new URLSearchParams()
  if (request.nameStrategy) params.append('nameStrategy', request.nameStrategy)
  if (request.namePrefix) params.append('namePrefix', request.namePrefix)
  if (request.tagStrategy) params.append('tagStrategy', request.tagStrategy)
  if (request.customTags?.length) {
    request.customTags.forEach((tag) => params.append('customTags', tag))
  }
  if (request.categoryStrategy) params.append('categoryStrategy', request.categoryStrategy)
  if (request.customCategory) params.append('customCategory', request.customCategory)
  if (request.spaceId) params.append('spaceId', request.spaceId)
  if (request.asyncAiProcess !== undefined)
    params.append('asyncAiProcess', request.asyncAiProcess.toString())

  return apiClient.post(`/picture/batch/upload?${params.toString()}`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

/**
 * 获取图片审核统计
 */
export const getPictureReviewCount = async (): Promise<ApiResponse<PictureReviewCountVO>> => {
  return apiClient.get('/picture/review/count')
}

/**
 * 获取空间图片的标签和分类
 */
export const listPictureTagCategoryBySpaceId = async (
  spaceId: string,
): Promise<ApiResponse<PictureTagCategory>> => {
  return apiClient.get(`/picture/tag_category/space?spaceId=${spaceId}`)
}

/**
 * 根据颜色搜索图片
 * @param request 搜索请求
 */
export const searchPictureByColor = async (
  request: SearchPictureByColorRequest,
): Promise<ApiResponse<PageResponse<PictureVO>>> => {
  return apiClient.post('/picture/search/color', request)
}

/**
 * 通过URL上传图片
 * @param request URL上传请求参数
 */
export const uploadPictureByUrl = async (
  request: PictureUploadRequest,
): Promise<ApiResponse<PictureVO>> => {
  return apiClient.post('/picture/upload/url', request)
}

/**
 * 获取图片风格重生成任务ID
 * @param request 风格重生成请求
 */
export const getPictureStyleRegenTaskId = async (request: PictureStyleRegenRequest) => {
  return styleReGenClient.post('/picture/style_regen', request)
}

/**
 * 获取图片风格重生成结果
 * @param taskId 任务ID
 */
export const getPictureStyleRegenResult = async (taskId: string) => {
  return styleReGenClient.get(`/picture/style_regen/task?taskId=${taskId}`)
}
